package com.wangmeng.book.client.frame;

import com.wangmeng.book.client.service.CommandService;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * User: 王猛
 * Date: 13-9-24
 */
public class LoginFrame implements ActionListener {
    private JPanel root;
    private JTextField userNameField;
    private JPasswordField passField;
    private JButton loginButton;
    private JButton resetButton;
    private JLabel titleLabel;
    private JPanel titlePanel;
    private JLabel userNameLabel;
    private JLabel passLabel;
    private JPanel buttonPanel;
    private JLabel messageLabel;

    private JDialog dialog;

    public LoginFrame() {
        loginButton.addActionListener(this);
        resetButton.addActionListener(this);
        passField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                super.keyPressed(e);
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    loginButton.doClick();
                }
            }
        });
    }


    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd != null) {
            if (cmd.equals("login")) {
                String userName = userNameField.getText();
                String pass = String.valueOf(passField.getPassword());
                if (userName != null && userName.trim().length() > 0 && pass != null && pass.length() > 0) {
                    boolean bc = CommandService.getInstance().login(userName, pass);
                    if (!bc) {
                        messageLabel.setText("登陆失败");
                    } else {
                        if (this.dialog != null) {
                            this.dialog.pack();
                            this.dialog.setVisible(false);
                            this.dialog = null;
                        }
                    }
                } else {
                    messageLabel.setText("参数录入错误");
                }
            } else if (cmd.equals("reset")) {
                messageLabel.setText("");
                userNameField.setText("");
                passField.setText("");
            }
        }
    }

    public void setDialog(JDialog dialog) {
        this.dialog = dialog;
    }

    public JPanel getRoot() {
        return root;
    }
}
